package com.tjetc.service.impl;

import com.tjetc.constant.CodeConstant;
import com.tjetc.constant.MessageConstant;
import com.tjetc.constant.RedisConstant;
import com.tjetc.domain.User;
import com.tjetc.repository.UserRepository;
import com.tjetc.service.UserService;
import com.tjetc.utils.JwtUtils;
import com.tjetc.utils.SendMessageUtil;
import com.tjetc.vo.OperationMessage;
import com.tjetc.vo.Result;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService{
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserRepository userRepository;

    @Override
    public Result verifyCode(String phone) {
        System.out.println("phone = " + phone);
        String code = null;
        try {
            code = SendMessageUtil.sendMessage(phone);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("服务器内部错误,发送短信失败");
        }
        if (code == null) {
            return Result.fail("服务器内部错误,发送短信失败");
        }
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set(RedisConstant.LOGIN_CODE_KEY+phone,code,5, TimeUnit.MINUTES);
        return Result.ok();
    }

    @Override
    public Result login(String phone, String code) {
        // 1. 验证码校验
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String oldCode = ops.get(RedisConstant.LOGIN_CODE_KEY + phone);

        if (oldCode == null) {
            return Result.fail("验证码不存在或者已过期");
        }

        if (!oldCode.equals(code)) {
            return Result.fail("验证码错误");
        }

        // 2. 检查用户状态
        User user = userRepository.findByPhone(phone);
        System.out.println("user = " + user);

        if (user == null) {
            // 新用户，返回未注册状态和手机号
            return new Result()
                    .setCode(CodeConstant.UNREGISTERED)
                    .setData(phone) // 只返回手机号用于注册
                    .setMsg("请完成注册");
        } else {
            // 已注册用户，生成token
            HashMap<String, Object> map = new HashMap<>();
            map.put("phone", phone);
            map.put("userId", user.getId());
            String token = jwtUtils.createJwtToken(map);

            return new Result()
                    .setCode(CodeConstant.SUCCESS)
                    .setData(token)
                    .setMsg("登录成功");
        }
    }

    // 新增注册方法
    @Override
    public Result register(User user) {
        try {
            // 验证必要字段
            if (user.getPhone() == null || user.getBirthday() == null) {
                return Result.fail("手机号和生日不能为空");
            }

            // 检查手机号是否已注册
            if (userRepository.findByPhone(user.getPhone()) != null) {
                return Result.fail("该手机号已注册");
            }

            // 设置创建时间
            user.setCreateTime(new Date());

            // 保存用户
            OperationMessage operationMessage = OperationMessage.add(user);
            rabbitTemplate.convertAndSend("topicExchange","topic.user",operationMessage);
//            userRepository.save(user);

            // 生成token
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("phone", user.getPhone());
            claims.put("userId", user.getId());
            String token = jwtUtils.createJwtToken(claims);

            return Result.ok(token);
        } catch (Exception e) {
            return Result.fail("注册失败: " + e.getMessage());
        }
    }

    @Override
    public Boolean importAll() {
        try {
            OperationMessage message = OperationMessage.importAll();
            rabbitTemplate.convertAndSend("topicExchange","topic.user",message);
            return true;
        } catch (AmqpException e) {
            e.printStackTrace();
        }
        return false;
    }
}
